/**
 * TodoListStore reducer
 *
 */

import { ADD_TODO, TOGGLE_TODO, REMOVE_TODO, UPDATE_TODO, TodoItem, TodoListActions } from './types';
import Utils from '../../../Common/Utils';

const initialState: TodoItem[] = Utils.store('todo_list') || [];

export const todoListReducer = (state = initialState, action: TodoListActions): TodoItem[] => {
  switch (action.type) {
    case ADD_TODO: {
      const todoList = [...state, action.payload];
      Utils.store('todo_list', todoList);
      return todoList;
    }
    case TOGGLE_TODO: {
      const todoList = [
        ...state.map(item => {
          if (item.id === action.payload.id) {
            if (typeof action.payload.isCompleted === 'boolean') {
              item.isCompleted = action.payload.isCompleted;
            } else {
              item.isCompleted = !item.isCompleted;
            }
          }
          return item;
        })
      ];
      Utils.store('todo_list', todoList);
      return todoList;
    }
    case UPDATE_TODO: {
      const todoList = [...state.map(item => (item.id === action.payload.id ? { ...item, title: action.payload.title } : item))];
      Utils.store('todo_list', todoList);
      return todoList;
    }
    case REMOVE_TODO: {
      const todoList = [...state.filter(item => item.id !== action.payload.id)];
      Utils.store('todo_list', todoList);
      return todoList;
    }
    default:
      return state;
  }
};
